package com.zf.http_interface.caller.controller;

import com.zf.http_interface.caller.entity.CustomByteArrayResource;
import com.zf.http_interface.caller.entity.CustomMultipartFile;
import com.zf.http_interface.caller.entity.UserInfo;
import com.zf.http_interface.caller.http_interface.BaseHttpInterfaceService;
import jakarta.annotation.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.StringJoiner;

/**
 * 调用测试
 */
@RestController
@RequestMapping("/test-call")
public class TestCallController {

    @Resource
    private BaseHttpInterfaceService baseHttpInterfaceService;

    /**
     * Get
     */
    @GetMapping("/get")
    public String testGet() {
        // Get
        System.out.println(baseHttpInterfaceService.hello("张三"));

        // 携带请求头 Get
        LinkedMultiValueMap<String, String> headerMap = new LinkedMultiValueMap<>();
        headerMap.add("auth", "111");
        headerMap.add("auth2", "222");
        System.out.println(baseHttpInterfaceService.hello2("李四", headerMap, "onxxxx"));

        // 单个参数 Get
        System.out.println(baseHttpInterfaceService.getUserInfo("李四33", 33));

        // 多个参数 Get
        LinkedMultiValueMap<String, Object> userInfoMap = new LinkedMultiValueMap<>();
        userInfoMap.add("username", "李四44");
        userInfoMap.add("age", 44);
        System.out.println(baseHttpInterfaceService.getUserInfo2(userInfoMap));

        // Get
        HashMap<String, Object> userInfoMap2 = new HashMap<>();
        userInfoMap2.put("username", "李四55");
        userInfoMap2.put("age", 55);
        System.out.println(baseHttpInterfaceService.getUserInfo3(userInfoMap2));

        return "success";
    }

    /**
     * PathVariable
     */
    @GetMapping("/pathVar")
    public UserInfo testPathVar() {
        UserInfo userInfo = baseHttpInterfaceService.getPathVar("小林", 13);
        System.out.println(userInfo);

        return userInfo;
    }


    /**
     * Post Json
     */
    @GetMapping("/postJson")
    public UserInfo testPostJson() {
        UserInfo userInfo = baseHttpInterfaceService.addUserInfo(new UserInfo("小明", 32));
        System.out.println(userInfo);

        return userInfo;
    }

    /**
     * 上传接口
     */
    @GetMapping("/uploadFile")
    public UserInfo testUploadFile() throws IOException {

        byte[] file1Bytes = createTxtFile("aaa");
        byte[] file2Bytes = createTxtFile("bbbbb");

        CustomMultipartFile file1 = new CustomMultipartFile(file1Bytes, "up-file1.txt");
        CustomMultipartFile file2 = new CustomMultipartFile(file2Bytes, "up-file2.txt");

        CustomByteArrayResource fileRes1 = new CustomByteArrayResource(file1Bytes, "up-file3.txt");
        CustomByteArrayResource fileRes2 = new CustomByteArrayResource(file2Bytes, "up-file4.txt");

        UserInfo userInfo = baseHttpInterfaceService.uploadFile("李四44", 88, Arrays.asList(file1, file2), Arrays.asList(fileRes1, fileRes2));

        System.out.println(userInfo);

        return userInfo;
    }

    /**
     * 下载接口
     */
    @GetMapping("/downloadFile")
    public String testDownloadFile() throws IOException {
        ResponseEntity<byte[]> response = baseHttpInterfaceService.downloadFile();
        // 获取响应体
        byte[] contentBytes = response.getBody();

        // 获取响应头的内容
        HttpHeaders headerMap = response.getHeaders();
        // 打印响应头
        StringJoiner headerStr = new StringJoiner("\n");
        headerMap.forEach((headerName, headerValueList) -> {
            headerStr.add(MessageFormat.format("{0}: {1}", headerName, String.join("|", headerValueList)));
        });
        System.out.println(headerStr);

        // Content-Disposition 响应头
        Collection<String> contentDisposition = headerMap.get(HttpHeaders.CONTENT_DISPOSITION);
        System.out.println(MessageFormat.format("文件：{0}, 大小：{1}", contentDisposition, contentBytes.length));

        String filename = "默认.zip";
        // 解析文件名
        if (!CollectionUtils.isEmpty(contentDisposition)) {
            // attachment;filename*=utf-8''%E4%B8%8B%E8%BD%BD%E6%96%87%E4%BB%B6.zip
            String cdHeaderValue = contentDisposition.stream().findFirst().get();
            cdHeaderValue = URLDecoder.decode(cdHeaderValue, StandardCharsets.UTF_8);
            String sep1 = "filename*=utf-8''";
            String sep2 = "filename=";
            if (cdHeaderValue.lastIndexOf(sep1) + sep1.length() < cdHeaderValue.length()) {
                filename = cdHeaderValue.substring(cdHeaderValue.lastIndexOf(sep1) + sep1.length()).replace("\"", "").replace("'", "");
            } else if (cdHeaderValue.lastIndexOf(sep2) + sep2.length() < cdHeaderValue.length()) {
                filename = cdHeaderValue.substring(cdHeaderValue.lastIndexOf(sep2) + sep2.length()).replace("\"", "").replace("'", "");
            }
        }

        // 将内容写入本地
        Files.write(Paths.get("D:\\" + filename), contentBytes);

        return "success";
    }

    /**
     * 创建一个txt文件，返回其内容的二进制
     */
    private byte[] createTxtFile(String content) throws IOException {
        // 创建一个 ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
        try (outputStreamWriter) {
            outputStreamWriter.write(content);
            outputStreamWriter.flush();
        }
        return outputStream.toByteArray();
    }

}
